package com.ruoyi.info.service.impl;

import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.ruoyi.common.core.domain.entity.SysDictData;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.info.domain.Auditing;
import com.ruoyi.info.domain.ProductForm;
import com.ruoyi.info.domain.Region;
import com.ruoyi.info.mapper.AuditingMapper;
import com.ruoyi.info.mapper.ProductFormMapper;
import com.ruoyi.info.mapper.RegionMapper;
import com.ruoyi.info.vo.AuditingEnterpriseBase;
import com.ruoyi.system.mapper.SysDictDataMapper;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.ss.util.CellRangeAddressList;
import org.apache.poi.xssf.usermodel.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.info.mapper.EnterpriseBaseMapper;
import com.ruoyi.info.domain.EnterpriseBase;
import com.ruoyi.info.service.IEnterpriseBaseService;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;

/**
 * 企业基地Service业务层处理
 * 
 * @author wangshi
 * @date 2023-06-06
 */
@Service
public class EnterpriseBaseServiceImpl implements IEnterpriseBaseService 
{
    @Autowired
    private EnterpriseBaseMapper enterpriseBaseMapper;

    @Autowired
    private AuditingMapper auditingMapper;

    @Autowired
    private SysDictDataMapper sysDictDataMapper;

    @Autowired
    private ProductFormMapper productFormMapper;

    @Autowired
    private RegionMapper regionMapper;

    /**
     * 查询企业基地
     * 
     * @param id 企业基地主键
     * @return 企业基地
     */
    @Override
    public EnterpriseBase selectEnterpriseBaseById(Long id)
    {
        return enterpriseBaseMapper.selectEnterpriseBaseById(id);
    }

    /**
     * 查询企业基地列表
     * 
     * @param enterpriseBase 企业基地
     * @return 企业基地
     */
    @Override
    public List<EnterpriseBase> selectEnterpriseBaseList(EnterpriseBase enterpriseBase)
    {
        return enterpriseBaseMapper.selectEnterpriseBaseList(enterpriseBase);
    }

    /**
     * 新增企业基地
     * 
     * @param enterpriseBase 企业基地
     * @return 结果
     */
    @Override
    public int insertEnterpriseBase(EnterpriseBase enterpriseBase)
    {
        enterpriseBase.setCreateTime(DateUtils.getNowDate());
        return enterpriseBaseMapper.insertEnterpriseBase(enterpriseBase);
    }

    /**
     * 修改企业基地
     * 
     * @param enterpriseBase 企业基地
     * @return 结果
     */
    @Override
    public int updateEnterpriseBase(EnterpriseBase enterpriseBase)
    {
        enterpriseBase.setUpdateTime(DateUtils.getNowDate());
        enterpriseBase.setEbState("0");
        return enterpriseBaseMapper.updateEnterpriseBase(enterpriseBase);
    }

    /**
     * 批量删除企业基地
     * 
     * @param ids 需要删除的企业基地主键
     * @return 结果
     */
    @Override
    public int deleteEnterpriseBaseByIds(Long[] ids)
    {
        return enterpriseBaseMapper.deleteEnterpriseBaseByIds(ids);
    }

    /**
     * 删除企业基地信息
     * 
     * @param id 企业基地主键
     * @return 结果
     */
    @Override
    public int deleteEnterpriseBaseById(Long id)
    {
        return enterpriseBaseMapper.deleteEnterpriseBaseById(id);
    }

    /**
     * 导出案例信息
     */
    @Override
    public void exportEnterpriseBase(HttpServletResponse response,EnterpriseBase enterpriseBase) throws IOException {
        List<EnterpriseBase> list = enterpriseBaseMapper.selectEnterpriseBaseList(enterpriseBase);
        XSSFWorkbook workbook = new XSSFWorkbook();
        try {

            XSSFSheet sheet = workbook.createSheet("企业基地");
            String[] labels = new String[]{
                    "企业名称",
                    "基地名称",
                    "所在省市",
                    "状态",
                    "投产日期",
                    "建厂形式",
                    "生产线(条)",
                    "产品固定产能(万台/年)",
                    "满产产能(万台)",
                    "现货库存(万台)",
                    "品牌",
                    "产品形态",
                    "备注",
                    "年度产能(万台)当前年",
                    "年度产能(万台)下一年"
            };
            XSSFRow headerRow = sheet.createRow(0);
            for (int j = 0; j < labels.length; j++) {
                XSSFCell countryCell = headerRow.createCell(j);

                countryCell.setCellValue(labels[j]);
            }
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            for (int i = 0; i < list.size(); i++) {
                XSSFRow row = sheet.createRow(i + 1);
//                    企业名称
                XSSFCell countryCell = row.createCell(0);
                countryCell.setCellValue(list.get(i).getEbName());
//                    基地名称
                XSSFCell countryCell1 = row.createCell(1);
                countryCell1.setCellValue(list.get(i).getEbBaseName());
//                    城市
                XSSFCell countryCell2 = row.createCell(2);
                countryCell2.setCellValue(list.get(i).getEbCity());
//                     状态
                XSSFCell countryCell3 = row.createCell(3);
                List<SysDictData> baseStatus = sysDictDataMapper.selectDictDataByType("base_status");
                for (int j = 0; j < baseStatus.size(); j++) {
                    if (list.get(i).getEbStatus().equals(baseStatus.get(j).getDictValue())) {
                        countryCell3.setCellValue(baseStatus.get(j).getDictLabel());
                        break;
                    }
                }

//                    投产日期
                XSSFCell countryCell4 = row.createCell(4);
                System.out.println(list.get(i).getEbProductionDate());

                countryCell4.setCellValue(sdf.format(list.get(i).getEbProductionDate()));
//                    建厂形式
                XSSFCell countryCell5 = row.createCell(5);
                List<SysDictData> factoryType = sysDictDataMapper.selectDictDataByType("factory_type");
                for (int j = 0; j < factoryType.size(); j++) {
                    if (list.get(i).getEbFactoryType().equals(factoryType.get(j).getDictValue())) {
                        countryCell5.setCellValue(factoryType.get(j).getDictLabel());
                        break;
                    }
                }
//                countryCell5.setCellValue(list.get(i).getEbFactoryType());
//                    生产线(条)
                XSSFCell countryCell6 = row.createCell(6);
                countryCell6.setCellValue(list.get(i).getEbProductionLine());
//                    产品固定产能(万台/年)
                XSSFCell countryCell7 = row.createCell(7);
                countryCell7.setCellValue(list.get(i).getEbFixedCapacity());
                //满产产能(万台)
                XSSFCell countryCell8 = row.createCell(8);
                countryCell8.setCellValue(list.get(i).getEbMaxCapacity());
                //  现货库存(万台)
                XSSFCell countryCell9 = row.createCell(9);
                countryCell9.setCellValue(list.get(i).getEbInventory());
                //  品牌
                XSSFCell countryCell10 = row.createCell(10);
                countryCell10.setCellValue(list.get(i).getEbBrand());
                //  产品形态
                XSSFCell countryCell11 = row.createCell(11);
                // 1,2#1,3 数据结构
                String[] split = list.get(i).getEbForm().split("#");
                List<String> formIds = new ArrayList<>();
                for (int j = 0; j < split.length; j++) {
                    String[] split1 = split[j].split(",");
                    for (int k = 0; k < split1.length; k++) {
                        formIds.add(split1[k]);
                    }
                }
                List<ProductForm> productForms = productFormMapper.selectProductFormIds(formIds);
                StringBuilder sb = new StringBuilder();
                productForms.stream().forEach(item -> {
                    sb.append(",");
                    sb.append(item.getName());
                });
                sb.deleteCharAt(0);
                countryCell11.setCellValue(sb.toString());
                //  技术路线
                XSSFCell countryCell12 = row.createCell(12);
                countryCell12.setCellValue(list.get(i).getEbTechnology());
                //  备注
                XSSFCell countryCell13 = row.createCell(13);
                countryCell13.setCellValue(list.get(i).getRemark());
                // 年度产能(万台)当前年
                XSSFCell countryCell14 = row.createCell(14);
                countryCell14.setCellValue(list.get(i).getEbCurrentCapacity());
                //  年度产能(万台)下一年
                XSSFCell countryCell15 = row.createCell(15);
                countryCell15.setCellValue(list.get(i).getEbNextRoadmap());
            }
            response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
            response.setCharacterEncoding("utf-8");
            workbook.write(response.getOutputStream());
        } finally {
            workbook.close();
        }
    }


    /**
     * 导出企业基地信息模板
     */
    public void templateDownload(HttpServletResponse response) throws IOException{
        XSSFWorkbook workbook = new XSSFWorkbook();

        try {
            XSSFSheet sheet = workbook.createSheet("企业基地");
            String[] labels = new String[]{
                    "基地名称",
                    "所在省市",
                    "状态",
                    "投产日期",
                    "建厂形式",
                    "生产线(条)",
                    "产品固定产能(万台/年)",
                    "满产产能(万台)",
                    "现货库存(万台)",
                    "品牌",
                    "产品形态",
                    "技术路线",
                    "备注",
                    "年度产能(万台)当前年",
                    "年度产能(万台)下一年"
            };
            XSSFRow headerRow = sheet.createRow(0);
            for (int j = 0; j < labels.length; j++) {
                XSSFCell countryCell = headerRow.createCell(j);
                ;
                countryCell.setCellValue(labels[j]);
            }

            // 创建行
            Row row1 = sheet.createRow(1);
            for (int i = 0; i < labels.length; i++) {
                // 创建单元格并设置值
                Cell cell = row1.createCell(i);

                if (i == 2) {
                    List<SysDictData> baseStatus = sysDictDataMapper.selectDictDataByType("base_status");
                    String[] dictLabels = new String[baseStatus.size()];
                    for (int j = 0; j < baseStatus.size(); j++) {
                        dictLabels[j] = baseStatus.get(j).getDictLabel();
                    }
                    // 设置单元格数据验证
                    DataValidationHelper validationHelper = new XSSFDataValidationHelper(sheet);
                    DataValidationConstraint constraint = validationHelper.createExplicitListConstraint(dictLabels);
                    CellRangeAddressList addressList = new CellRangeAddressList(0, 400, i, i);
                    DataValidation validation = validationHelper.createValidation(constraint, addressList);
                    sheet.addValidationData(validation);
                }
                if (i == 3) {
                    // 设置日期格式
                    String dateFormat = "yyyy-mm-dd";
                    DataFormat dataFormat = workbook.createDataFormat();
                    CellStyle dateStyle = workbook.createCellStyle();
                    dateStyle.setDataFormat(dataFormat.getFormat(dateFormat));
                    cell.setCellStyle(dateStyle);
                }
                if (i == 4) {
                    List<SysDictData> factoryType = sysDictDataMapper.selectDictDataByType("factory_type");
                    String[] dictLabels = new String[factoryType.size()];
                    for (int j = 0; j < factoryType.size(); j++) {
                        dictLabels[j] = factoryType.get(j).getDictLabel();
                    }
                    // 设置单元格数据验证
                    DataValidationHelper validationHelper = new XSSFDataValidationHelper(sheet);
                    DataValidationConstraint constraint = validationHelper.createExplicitListConstraint(dictLabels);
                    CellRangeAddressList addressList = new CellRangeAddressList(0, 400, i, i);
                    DataValidation validation = validationHelper.createValidation(constraint, addressList);
                    sheet.addValidationData(validation);
                }
                if (i == 10) {
                    List<ProductForm> productForms = productFormMapper.selectProductFormList(new ProductForm());
                    String[] dictLabels = new String[productForms.size()];
                    for (int j = 0; j < productForms.size(); j++) {
                        dictLabels[j] = productForms.get(j).getLevelName().replace(",","-");
                    }
                    // 设置单元格数据验证
                    DataValidationHelper validationHelper = new XSSFDataValidationHelper(sheet);
                    DataValidationConstraint constraint = validationHelper.createExplicitListConstraint(dictLabels);
                    CellRangeAddressList addressList = new CellRangeAddressList(0, 400, i, i);
                    DataValidation validation = validationHelper.createValidation(constraint, addressList);
                    sheet.addValidationData(validation);
                }
                cell.setCellValue("");
            }
            response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
            response.setCharacterEncoding("utf-8");
            workbook.write(response.getOutputStream());
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            workbook.close();
        }
    }

    /**
     * 导入企业基地信息模板-解析模板数据
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int templateRender(MultipartFile file) throws IOException{
        // 创建工作簿对象
        Workbook workbook = new XSSFWorkbook(file.getInputStream());
        try {

            // 获取第一个工作表
            Sheet sheet = workbook.getSheetAt(0);
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            int i = 0;
            // 遍历行
            for (Row row : sheet) {
                if(i == 0){
                    i++;
                    continue;
                }
                EnterpriseBase enterpriseBase = new EnterpriseBase();
                int j = 0;
                // 遍历单元格
                for (Cell cell : row) {

                    // 获取单元格的值
                    CellType type = cell.getCellType();
                    String value = "";
                    if (type == CellType.STRING) {
                        value = cell.getStringCellValue();

                    } else if (type == CellType.NUMERIC) {
                        if(j == 3){
                            value = sdf.format(DateUtil.getJavaDate(cell.getNumericCellValue()));
                        }else{
                            value = String.valueOf(cell.getNumericCellValue());
                        }

                    } else if (type == CellType.BOOLEAN) {
                        value = String.valueOf(cell.getBooleanCellValue());
                    }

                    if(j == 0){
                        enterpriseBase.setEbBaseName(value);
                    }else if(j == 1){
                        String city = value.replace("-",",");
                        Region region = new Region();
                        region.setLevelName(city);
                        List<Region> regions = regionMapper.selectRegionList(region);
                        if(regions.size() > 0){
                            enterpriseBase.setEbAddress(regions.get(0).getLevelCode());
                        }

                        enterpriseBase.setEbCity(city);
                    }else if(j == 2){
                        List<SysDictData> baseStatus = sysDictDataMapper.selectDictDataByType("base_status");
                        for (int K= 0; K < baseStatus.size(); K++) {
                            if (value.equals(baseStatus.get(K).getDictLabel())) {
                                enterpriseBase.setEbStatus(baseStatus.get(K).getDictValue());
                                break;
                            }
                        }
                    }else if(j == 3){
                        enterpriseBase.setEbProductionDate(sdf.parse(value));
                    }else if(j == 4){
                        List<SysDictData> factoryType = sysDictDataMapper.selectDictDataByType("factory_type");
                        for (int K= 0; K < factoryType.size(); K++) {
                            if (value.equals(factoryType.get(K).getDictLabel())) {
                                enterpriseBase.setEbFactoryType(factoryType.get(K).getDictValue());
                                break;
                            }
                        }
                    }else if(j == 5){
                        enterpriseBase.setEbProductionLine(value);
                    }else if(j == 6){
                        enterpriseBase.setEbFixedCapacity(value);
                    }else if(j == 7){
                        enterpriseBase.setEbMaxCapacity(value);
                    }else if(j == 8){
                        enterpriseBase.setEbInventory(value);
                    }else if(j == 9){
                        enterpriseBase.setEbBrand(value);
                    }else if(j == 10){
                        value = value.replace("-",",");
                        ProductForm productForm = new ProductForm();
                        productForm.setLevelName(value);
                        List<ProductForm> productForms = productFormMapper.selectProductFormList(productForm);
                        if(productForms.size() > 0){
                            enterpriseBase.setEbForm(productForms.get(0).getLevelCode());
                        }
                    }else if(j == 11){
                        enterpriseBase.setEbTechnology(value);
                    }else if(j == 12){
                        enterpriseBase.setRemark(value);
                    }else if(j == 13){
                        enterpriseBase.setEbCurrentCapacity(value);
                    }else if(j == 14){
                        enterpriseBase.setEbNextRoadmap(value);
                    }


                    j++;
                }
                enterpriseBase.setEbName("单位一");
                enterpriseBaseMapper.insertEnterpriseBase(enterpriseBase);
            }

        } catch (ParseException e) {
            throw new RuntimeException(e);
        } finally {
            workbook.close();
        }

        return 1;
    };


    /**
     * 企业基地审核
     * @param auditingEnterpriseBase 企业基地审核字段
     * @return
     */
    @Override
    @Transactional
    public int auditingEnterpriseBase(AuditingEnterpriseBase auditingEnterpriseBase){
        EnterpriseBase enterpriseBase = new EnterpriseBase();
        enterpriseBase.setId(auditingEnterpriseBase.getaPId());
        enterpriseBase.setEbState(auditingEnterpriseBase.getEbState());
        enterpriseBase.setUpdateBy(auditingEnterpriseBase.getCreateBy());
        enterpriseBase.setUpdateTime(DateUtils.getNowDate());
        int i = enterpriseBaseMapper.updateEnterpriseBase(enterpriseBase);
        if(i>0){
            Auditing auditing = new Auditing();
            auditing.setpName("enterprise_base");
            auditing.setaPId(auditingEnterpriseBase.getaPId());
            auditing.setaInfo(auditingEnterpriseBase.getaInfo());
            auditing.setaState(auditingEnterpriseBase.getEbState());
            auditing.setCreateTime(DateUtils.getNowDate());
            auditing.setCreateBy(auditingEnterpriseBase.getCreateBy());
            return auditingMapper.insertAuditing(auditing);
        }
        return 0;
    };


    /**
     * 全国省份生产基地数量排名
     * @param name 企业名称
     * @return 同比增长
     */
    public List<Map<String, String>> selectRanking(String name){
        return enterpriseBaseMapper.selectRanking(name);
    }

    /**
     * 企业供货产品满产产能趋势
     * @param name 企业名称
     * @return 同比增长
     */
    public  List<Map<String,String>> selectCapacity(String name){
        return enterpriseBaseMapper.selectCapacity(name);
    }
    /**
     * 企业供货产品类型分布
     * @param name 企业名称
     * @return 同比增长
     */
    public  List<Map<String,String>> selectProductTypeDistribution(String name){
        return enterpriseBaseMapper.selectProductTypeDistribution(name);
    }

    /**
     * 企业统计基本信息
     * @param name 企业名称
     * @return 同比增长
     */
    public  Map<String,String> selectBasicInfo(String name){
        Map<String, String> info = new HashMap<>();
//        根据企业名称企业基地总数
        info.put("count",  String.valueOf(enterpriseBaseMapper.selectCount(name)));
//        根据企业名称同比增长
        Double v = enterpriseBaseMapper.selectGrowthResult(name);
        Double growthDouble = enterpriseBaseMapper.selectGrowth(name);

        String growth = "0";
        if(growthDouble != null){
            growth = String.valueOf(growthDouble);

            if(v != null){
                if(v>0){
                    growth = "+"+growth;
                }else{
                    growth = "-"+growth;
                }
            }
        }



        info.put("growth",growth);
//        根据企业名称 总产能
        String sumGrowth = "0";
        Integer sumGrowthInt = enterpriseBaseMapper.selectCountCapacity(name);
        if(sumGrowthInt != null){
            sumGrowth = String.valueOf(sumGrowthInt);
        }
        info.put("sumGrowth",sumGrowth);
//        据企业名称查询生产线总数
        String sumProductionLine = "0";
        Integer sumProductionLineInt = enterpriseBaseMapper.selectSumProductionLine(name);
        if(sumProductionLineInt != null){
            sumProductionLine = String.valueOf(sumProductionLineInt);
        }
        info.put("sumProductionLine",sumProductionLine);

        return info;
    }
}
